<template>
  <div class="create-component-list">
    <div v-for="(item, index) in list" :key="index" class="component-item" @click="onItemClick(item)">
      <l-text v-bind="item"></l-text>
    </div>
  </div>
  <StyledUploader @success="onImageUploaded"></StyledUploader>
</template>

<script lang="ts" setup>
import LText from './LText.vue'
import { v4 as uuidv4 } from 'uuid'
import { message } from 'ant-design-vue'
import StyledUploader from '../components/StyledUploader.vue'

import { imageDefaultProps, type TextComponentProps } from 'lego-bricks'
import type { ComponentData } from '@/stores/modules/editor/interface'
import type { RespUploadData } from '@/stores/modules/respTypes/type'
import { getImageDimensions } from '@/utils/helper'


defineOptions({
  name: 'components-list'
})

defineProps({
  list: {
    type: Array as any,
    required: true
  }
})

const emit = defineEmits(['on-item-click'])
const onItemClick = (props: TextComponentProps) => {
  const componentData: ComponentData = {
    name: 'l-text',
    id: uuidv4(),
    props
  }
  emit('on-item-click', componentData)
}
const onImageUploaded = (data: { resp: RespUploadData; file: File }) => {
  const { resp, file } = data
  const componentData: ComponentData = {
    name: 'l-image',
    id: uuidv4(),
    props: {
      ...imageDefaultProps
    }
  }
  message.success('上传成功')
  componentData.props.src = resp.data.urls[0]
  getImageDimensions(file).then(({ width }) => {
    const maxWidth = 373
    componentData.props.width = ((width > maxWidth) ? maxWidth : width) + 'px'
    emit('on-item-click', componentData)
  })
}
</script>

<style>
.component-item {
  width: 100px;
  margin: 0 auto;
  margin-bottom: 15px;
}

.component-item>* {
  position: static !important;
}
</style>
